<?php

namespace Beerus\Modules\DesignerCompetition2020\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\DesignerCompetition2020\Actions\EditAward;
use Doraemon\model\Article;
use Doraemon\model\ArticleHouse;
use Doraemon\model\DesignerCompetition\DesignerAwardSign2020;
use Doraemon\model\Member;
use Doraemon\service\admin\EnterAward;
use Doraemon\service\DesignerCompetition2020\SignService;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;

/**
 * 大赛评审
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */

class AuditController extends Controller
{
    const PAGE_SIZE = 10;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    /**
     * 大赛报名列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content)
    {
        $request_params = $request->all();

        $page_size = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);

        $condition = $this->condition($request_params);

        // 查询报名总人数
        $sign_num = DesignerAwardSign2020::signUserCount($condition);
        $tips = "<div class='alert alert-info'>共{$sign_num}个账号报名</div>";

        return $content
            ->header('大赛报名列表')
            ->row($tips)
            ->row($this->indexGrid($condition, $page, $page_size));
    }

    /**
     * 表格展示部分
     * @param $condition
     * @return Grid
     */
    public function indexGrid($condition, $page, $page_size)
    {
        Admin::script($this->jumpScript());

        $lists = DesignerAwardSign2020::getListByCondition($condition, $page, $page_size);
        $total = DesignerAwardSign2020::countListByCondition($condition);

        if (!empty($lists)) {
            $user_ids = array_column($lists, 'uid');
            $member_info = Member::getUsers($user_ids);

            foreach ($lists as &$item) {
                $user_type = $member_info[$item['uid']]['type'];

                // 用户信息
                $item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
                $item['user_type'] = SignService::USER_TYPE[$user_type];

                // 参赛信息
                $item['from_name'] = SignService::FROM[$item['channel']];
                $item['area'] = SignService::AREA[$item['area']];
                $item['house_model'] = SignService::HOUSE_MODEL[$item['house_model']];
                $is_plane = '否';
                if ($item['award_type'] == DesignerAwardSign2020::DESIGNER_BEST_PLANE_AWARD ||
                    $item['award_type'] == DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD) {
                    $is_plane = '是';
                }
                $item['is_plane'] = $is_plane;
                $is_soft = '否';
                if ($item['award_type'] == DesignerAwardSign2020::DESIGNER_BEST_SOFT_AWARD ||
                    $item['award_type'] == DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD) {
                    $is_soft = '是';
                }
                $item['is_soft'] = $is_soft;
                $item['sign_time'] = date('Y-m-d H:i:s', $item['add_time']);

                // 作品链接
                if ($item['channel'] == DesignerAwardSign2020::FROM_OWNER) {
                    $article_info = Article::getArticle($item['article_id']);
                    $item['work_name'] = empty($article_info) ? '作品名称无' : $article_info['title'];
                    $item['link'] = Hhzurl::getDomain() . "/bangyang/{$item['article_id']}.html";
                    $item['work_pic_url'] = ImgUrl::getUrl(
                        ImgUrl::APPTYPE_APP,
                        $article_info['cover_pic_id'],
                        ImgUrl::IMAGE_SIZE_SQ_PHONE
                    );
                } elseif ($item['channel'] == DesignerAwardSign2020::FROM_DESIGNER) {
                    $live_photos = json_decode($item['live_photos'], true);
                    $item['live_photos'] = $live_photos;
                    $work_pic_url = ImgUrl::getUrl(
                        ImgUrl::APPTYPE_APP,
                        $live_photos[0]['pic_id'],
                        ImgUrl::IMAGE_SIZE_SQ_PHONE
                    );
                    $item['work_pic_url'] = $work_pic_url; // 取实景作品的第一条

                    $item['link'] = Hhzurl::getDomain() . "/designer/game/2020/production-detail?id={$item['id']}";
                }

                // 作品信息
                $article_house = ArticleHouse::getArticleHouseById($item['article_id']);

                $item['house_construction'] = $item['house_stuff'] = $item['house_area'] = '';
                if (!empty($article_house)) {
                    // 户型
                    $house_arr = explode(',', $article_house['house_construction']);
                    $item['house_construction'] = $house_arr[0] . '室';
                    // 房屋所在地
                    $item['house_area'] = $article_house['area_name'];
                }

                // 常住人口
                if ($item['people'] == 5) {
                    $people = $item['other_people'];
                } else {
                    $people = DesignerAwardSign2020::PEOPLE[$item['people']];
                }
                $item['people'] = $people;
            }
            unset($item);
        }

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => self::PAGE_SIZE,
        ]);

        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function ($filter) {
                        // 用户身份
                        $filter->equal('user_type', '用户身份')->select(SignService::USER_TYPE_MAP);
                        // 报名通道
                        $filter->equal('channel', '报名通道')->select(SignService::FROM);
                        // 赛区
                        $filter->equal('area', '赛区')->select(SignService::AREA);
                        // 户型
                        $filter->equal('house_model', '户型')->select(SignService::HOUSE_MODEL);
                        // 评审结果
                        $filter->equal('audit_status', '评审结果')->select(SignService::AUDIT_STATUS_MAP);
                        // 获得奖项
                        $filter->equal('award_id', '获得奖项')->select(EnterAward::getAvailAward(2020));
                    });

                    $filter->column(1 / 2, function ($filter) {
                        $options = ['' => '全部', '1' => '是', '2' => '否'];
                        // 勾选平面
                        $filter->equal('is_plane', '勾选平面')->radio($options);
                        // 勾选软装
                        $filter->equal('is_soft', '勾选软装')->radio($options);
                        // 包含备注
                        $filter->equal('is_remark', '包含备注')->radio($options);
                        // 备注内容
                        $filter->equal('remark', '备注内容');
                        // 用户uid
                        $filter->equal('uid', '用户uid');
                        $filter->equal('id', '报名id');
                    });
                    $filter->expand();
                });

                $grid->column('id', '报名id')->width(70);
                $grid->column('user_info', '用户信息')->width(140)->display(function () {
                    $userInfo[] = 'uid：' . $this->uid;
                    $userInfo[] = '昵称：<a class="jump_user" href="javascript:void(0);"> ' . $this->nick . '</a>';
                    $userInfo[] = '身份：' . $this->user_type;
                    return implode('<br/>', $userInfo);
                });

                $grid->column('competition_info', '参赛信息')->width(240)->display(function () {
                    if ($this->channel == DesignerAwardSign2020::FROM_OWNER) {
                        $competition_info[] = '通道：' . $this->from_name;
                        $competition_info[] = '报名时间：' . $this->sign_time;

                        return implode('<br/>', $competition_info);
                    } elseif ($this->channel == DesignerAwardSign2020::FROM_DESIGNER) {
                        $competition_info[] = '通道：' . $this->from_name;
                        $competition_info[] = '赛区：' . $this->area;
                        $competition_info[] = '户型：' . $this->house_model;
                        $competition_info[] = '软装：' . $this->is_soft;
                        $competition_info[] = '平面：' . $this->is_plane;
                        $competition_info[] = '报名时间：' . $this->sign_time;

                        return implode('<br/>', $competition_info);
                    } else {
                        return '报名入口来源未知';
                    }
                });

                $grid->column('work_link', '作品链接')->width(210)->display(function () {
                    $open = isset($this->work_name) ? '<a class="fa " href="javascript:layer.open({type: 2,
                    title: \'预览\', maxmin: true, area: [\'650px\', \'700px\'],
                    content: \'' . $this->link . '\' });">' . htmlentities($this->work_name) . '</a>' : "";
                    $img = "<img width='200' height='200' src='{$this->work_pic_url}'>";

                    if ($this->channel == DesignerAwardSign2020::FROM_OWNER) {
                        return implode('<br/>', [$img, $open]);
                    } elseif ($this->channel == DesignerAwardSign2020::FROM_DESIGNER) {
                        $download = "<a href='/admin/DesignerCompetition2020/download/{$this->id}'
                        style='color: darkblue'>下载图片</a>";
                        return implode('<br/>', [$img, $open, $download]);
                    }
                });

                $grid->column('work_info', '作品信息')->width(400)->display(function () {
                    $work_info = [];
                    if ($this->channel == DesignerAwardSign2020::FROM_OWNER) {
                        return '无';
                    } elseif ($this->channel == DesignerAwardSign2020::FROM_DESIGNER) {
                        $work_info[] = '户型：' . $this->house_construction;
                        $work_info[] = '总造价：' . $this->total_price . '万元';
                        $work_info[] = '地区：' . $this->house_area;
                        $work_info[] = '常住人口：' . $this->people;
                        $work_info[] = '项目完成时间：' . $this->design_finish_date;
                        $work_info[] = '满意的产品：' . $this->most_satisfied;
                        $work_info[] = '产品品牌：' . $this->satisfied_brand;
                        $work_info[] = '满意的原因：' . $this->satisfied_reason;

                        return implode('<br/>', $work_info);
                    } else {
                        return '报名入口来源未知';
                    }
                });

                $grid->column('audit_status', '评审结果')->width(100)->radio(SignService::AUDIT_STATUS_MAP);

                $grid->column('remark', '备注')->width(200)->editable();

                $grid->setActionClass(DropdownActions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
                    $actions->add(new EditAward);
                });
            }
        );

        return $gridList;
    }

    private function condition($request)
    {
        $response = [];

        // 用户uid
        if (isset($request['uid']) && ($request['uid'] !== '')) {
            $response['uid'] = $request['uid'];
        }

        // 用户身份
        if (isset($request['user_type']) && ($request['user_type'] !== '')) {
            $response['user_type'] = $request['user_type'];
        }

        // 报名通道
        if (isset($request['channel']) && ($request['channel'] > 0)) {
            $response['channel'] = $request['channel'];
        }

        // 赛区
        if (isset($request['area']) && ($request['area'] != '')) {
            $response['area'] = $request['area'];
        }

        // 户型
        if (isset($request['house_model']) && ($request['house_model'] !== '')) {
            $response['house_model'] = $request['house_model'];
        }

        // 评审结果
        if (isset($request['audit_status']) && ($request['audit_status'] !== '')) {
            $response['audit_status'] = $request['audit_status'];
        }

        if ($request['is_plane'] == 1) {
            if ($request['is_soft'] == '') {
                $response['award_type'] = [
                    DesignerAwardSign2020::DESIGNER_BEST_PLANE_AWARD,
                    DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD
                ];
            } elseif ($request['is_soft'] == 1) {
                $response['award_type'] = DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD;
            } elseif ($request['is_soft'] == 2) {
                $response['award_type'] = DesignerAwardSign2020::DESIGNER_BEST_PLANE_AWARD;
            }
        } elseif ($request['is_plane'] == 2) {
            if ($request['is_soft'] == '') {
                $response['award_type'] = [
                    0,
                    DesignerAwardSign2020::DESIGNER_BEST_SOFT_AWARD,
                    DesignerAwardSign2020::OWNER_REFERRAL_AWARD
                ];
            } elseif ($request['is_soft'] == 1) {
                $response['award_type'] = DesignerAwardSign2020::DESIGNER_BEST_SOFT_AWARD;
            } elseif ($request['is_soft'] == 2) {
                $response['award_type'] = [
                    DesignerAwardSign2020::OWNER_REFERRAL_AWARD,
                    0
                ];
            }
        }

        if ($request['is_soft'] == 1) {
            if ($request['is_plane'] == 0) {
                $response['award_type'] = [
                    DesignerAwardSign2020::DESIGNER_BEST_SOFT_AWARD,
                    DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD
                ];
            } elseif ($request['is_plane'] == 1) {
                $response['award_type'] = DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD;
            } elseif ($request['is_plane'] == 2) {
                $response['award_type'] = DesignerAwardSign2020::DESIGNER_BEST_SOFT_AWARD;
            }
        } elseif ($request['is_soft'] == 2) {
            if ($request['is_plane'] == '') {
                $response['award_type'] = [
                    0,
                    DesignerAwardSign2020::DESIGNER_BEST_PLANE_AWARD,
                    DesignerAwardSign2020::OWNER_REFERRAL_AWARD
                ];
            } elseif ($request['is_plane'] == 1) {
                $response['award_type'] = DesignerAwardSign2020::DESIGNER_BEST_PLANE_AWARD;
            } elseif ($request['is_plane'] == 2) {
                $response['award_type'] = [
                    DesignerAwardSign2020::OWNER_REFERRAL_AWARD,
                    0
                ];
            }
        }

        // 备注
        if (isset($request['is_remark']) && ($request['is_remark'] > 0)) {
            if ($request['is_remark'] == 1) {
                // 备注匹配
                if (isset($request['remark']) && ($request['remark'] !== '')) {
                    $response['remark[~]'] = $request['remark'];
                } else {
                    $response['remark[!]'] = '';
                }
            } elseif ($request['is_remark'] == 2) {
                // 备注匹配
                if (isset($request['remark']) && ($request['remark'] !== '')) {
                    $response['id'] = 0;
                } else {
                    $response['remark'] = '';
                }
            }
        }

        // 备注匹配
        if (isset($request['remark']) && ($request['remark'] !== '')) {
            $response['remark[~]'] = $request['remark'];
        }

        if (!empty($request['id'])) {
            $response = [
                'id' => $request['id'],
            ];
        }

        if (!empty($request['award_id'])) {
            $response['award_id'] = $request['award_id'];
        }

        return $response;
    }

    private function jumpScript()
    {
        return <<<SCRIPT
        // 用户详情跳转
        $('.jump_user').unbind('click').click(function(){
            let win = window.open('http://manage.haohaozhu.me/','用户详情','name=用户详情');
            win.openapp('/User/Oauthadmin/detail/uid/608209','user_detail608209','用户详情');
        });

        $('.btn-xs').hide();

        $("input[name='grid-radio-audit_status']").change(
		function() {
		        id = $(this).parents('.grid-radio-audit_status')[0].getAttribute('data-key');
                var audit_status = $(this).val();

                $.ajax({
                    url:'/admin/DesignerCompetition2020/audit/' + id,
                    type:"POST",
                    data: {_method:"PUT", audit_status: audit_status},
                    dataType:"json",
                    success:function(result){
                        if (result.status) {
                            toastr.success(result.message);
                        } else {
                            toastr.warning(result.message);
                        }
                    },
                    error:function(){
                        toastr.error('系统错误,请联系管理员');
                    }
                });
	    });
SCRIPT;
    }

    public function save(Request $request, $id)
    {
        $pjax = true;
        $status = true;
        $name = $request->input('name');
        $value = $request->input('value');
        $audit_status = $request->input('audit_status');

        $message = "修改成功";
        try {
            if (isset($name) && isset($value)) {
                switch ($name) {
                    case 'remark':
                        $pjax = false;
                        if (mb_strlen($value) > 300) {
                            throw new \Exception('最多300字');
                        }
                        DesignerAwardSign2020::update(['remark' => $value], ['id' => $id]);
                        break;
                    default:
                        throw new \Exception('未开发功能');
                        break;
                }
            } elseif (isset($audit_status)) {
//                if ($audit_status == SignService::AUDIT_STATUS_UNDONE) {
                //                    throw new \Exception('不支持回到未审核');
                //                }
                DesignerAwardSign2020::update(['audit_status' => $audit_status], ['id' => $id]);
            } else {
                throw new \Exception('缺少参数错误');
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();

            if (!$pjax) {
                return response()->json(['errors' => [$message]], 422);
            }
        }

        return response()->json(compact('message', 'status'));
    }

    public function download($id)
    {
        // 查询当前报名作品的图片信息
        $sign_info = DesignerAwardSign2020::getById($id);
        $photos = [];
        if (!empty($sign_info['plane_photos'])) {
            $plane_photo = json_decode($sign_info['plane_photos'], true);
            foreach ($plane_photo as $item) {
                $photos[] = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $item['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            }
        }

        if (!empty($sign_info['live_photos'])) {
            $live_photos = json_decode($sign_info['live_photos'], true);
            foreach ($live_photos as $item) {
                $photos[] = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $item['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            }
        }

        $save_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'sign_image' . DIRECTORY_SEPARATOR . $id;

        if (!is_dir($save_path)) {
            mkdir($save_path, 0777, true);
        }

        foreach ($photos as $url) {
            $file_name = $save_path . DIRECTORY_SEPARATOR . md5($url) . '.jpeg';
            if (!file_exists($file_name)) {
                file_put_contents($file_name, file_get_contents($url));
            }
        }

        // 压缩打包文件
        $outputs = [];
        exec("cd {$save_path}; zip -r {$save_path} ". DIRECTORY_SEPARATOR ."image.zip ./ ", $outputs, $rc);
        $file = "/tmp/sign_image/{$id}.zip";
        $fp = fopen($file, "r");
        if (file_exists($file)) {
            exec("rm -rf  {$save_path}". DIRECTORY_SEPARATOR, $outputs, $rc);
            ob_end_clean();

            $file_size = filesize($file);
            header("Content-type:application/octet-stream");
            header("Accept-Ranges:bytes");
            header("Accept-Length:" . $file_size);
            header("Content-Disposition: attachment;filename={$id}.zip");

            $buffer = 1024;
            $file_count = 0;

            while (!feof($fp) && $file_count < $file_size) {
                $file_con = fread($fp, $buffer);
                $file_count += $buffer;
                echo $file_con;
            }

            fclose($fp);
            if ($file_count >= $file_size) {
                unlink($file);
            }

            return response()->json(['errors' => ['no']], 422);
        }
    }
}
